layui.use(['layer', 'form', 'jquery', 'table'], function () {
    var layer = layui.layer;
    var form = layui.form;
    var $ = layui.jquery;
    var table = layui.table;
    //获取使用人id
    var createId = localStorage.getItem('createId');
    //树
    var settingss = {
        view: {
            dblClickExpand: false,
            addDiyDom: addDiyDom
        },
        data: {
            simpleData: {
                enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式
                idKey: "acticleCategroyId",
                pIdKey: "artcleCatefroyParentId",
                rootPId: -1  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
            },
            key: {
                enable: true,
                name: "artcleCategroyName"
            }
        },
        check: {
            enable: false,
            nocheckInherit: true   //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
        },
        callback: {
            onRightClick: onRightClick,
            beforeRename: beforeRename,//编辑结束时触发，用来验证输入的数据是否符合要求(也是根据返回值 true|false 确定是否可以编辑完成)
            onClick: chooseNode,
        }
    };

    //显示6个，多余的省略
    function addDiyDom(treeId, treeNode) {
        var spaceWidth = 6;
        var switchObj = $("#" + treeNode.tId + "_switch"),
            icoObj = $("#" + treeNode.tId + "_ico");
        switchObj.remove();
        icoObj.parent().before(switchObj);
        var spantxt = $("#" + treeNode.tId + "_span").html();
        if (spantxt.length > 6) {
            spantxt = spantxt.substring(0, 6) + "...";
            $("#" + treeNode.tId + "_span").html(spantxt);
        }
    }

    //鼠标右键功能
    function onRightClick(event, treeId, treeNode) {
        if (treeNode && !treeNode.noR) {
            zTree.selectNode(treeNode);
            showRMenu("node", event.clientX, event.clientY);
        }
    }

    //修改前判断
    function beforeRename(treeId, treeNode, newName) {
        if (newName.length == 0) {
            layer.msg("节点名称不能为空.");
            var zTree = $.fn.zTree.getZTreeObj("ztree");
            setTimeout(function () {
                zTree.editName(treeNode)
            }, 10);
            return false;
        }
        return true;
    }

    function showRMenu(type, x, y) {
        $("#rMenu ul").show();
        if (type == "root") {
            $("#m_del").hide();
        } else {
            $("#m_del").show();
        }

        y += document.body.scrollTop;
        x += document.body.scrollLeft;
        rMenu.css({"top": y + "px", "left": x + "px", "visibility": "visible"});
        $("body").bind("mousedown", onBodyMouseDown);
    }

    function hideRMenu() {
        if (rMenu) rMenu.css({"visibility": "hidden"});
        $("body").unbind("mousedown", onBodyMouseDown);
    }

    function onBodyMouseDown(event) {
        if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
            rMenu.css({"visibility": "hidden"});
        }
    }

    //添加节点
    addTreeNode = function addTreeNode() {
        hideRMenu();
        //获取节点信息
        var nodes = zTree.getSelectedNodes();
        var artcleCatefroyParentId = nodes[0].acticleCategroyId;
        layer.open({
            type: 1,
            title: "添加微圈",
            area: ['400px', '250px'],
            shade: 0.4,
            offset: 'auto',
            content: "<form class='layui-form'><div class='layui-form-item' style='margin: 20px;'>" +
                "<label class='layui-input-label'>微圈分类：</label>"
                + "<input type='text' name='title' style='width:220px;height:30px;'id='addNode' lay-verify='required' placeholder='请输入微圈分类名称'>"
                + "</div></form>",
            btn: ['添加', '取消'],
            yes: function () {
                var artcleCategroyName = $("#addNode").val();
                var jsActicleCategroy = {
                    'artcleCatefroyParentId': artcleCatefroyParentId,
                    'artcleCategroyName': artcleCategroyName,
                    'createId': createId,
                }
                $.ajax({
                    url: '/acticleCategroy/addActicleCategroy',
                    type: 'post',
                    dataType: 'json',
                    data: jsActicleCategroy,
                    success: function (data) {
                        if (data.data) {
                            layer.msg("添加成功");
                            location.reload();
                        } else {
                            layer.msg("添加失败");
                        }
                    }
                });
            }
        })
    }
    //删除节点
    removeTreeNode = function removeTreeNode() {
        hideRMenu();
        //获取节点信息
        var nodes = zTree.getSelectedNodes();
        var acticleCategroyId = nodes[0].acticleCategroyId;
        layer.confirm("确认删除" + nodes[0].artcleCategroyName + "微圈分类?", {icon: 3, title: '提示'}, function (index) {
            if (nodes[0].isParent) {
                layer.msg("不能删除该目录，请从最底层目录开始删除!");
                return false;
            }
            $.ajax({
                url: '/acticleCategroy/deleteActicleCategroy',
                type: 'post',
                data: {"acticleCategroyId": acticleCategroyId},
                dataType: 'json',
                success: function (data) {
                    if (data.data) {
                        layer.msg("删除成功");
                        location.reload();
                        return true;
                    } else {
                        layer.msg("删除失败");
                        return false;
                    }
                }
            });
        })
    }
    //修改节点
    edit = function edit() {
        hideRMenu();
        //获取节点信息
        var nodes = zTree.getSelectedNodes();
        var acticleCategroyId = nodes[0].acticleCategroyId;
        layer.open({
            type: 1,
            title: '修改微圈',
            area: ['400px', '250px'],
            shade: 0,
            offset: 'auto',
            content: "<form class='layui-form'><div class='layui-form-item' style='margin: 20px;'>" +
                "<label class='layui-input-label'>微圈分类：</label>"
                + "<input type='text' name='title' style='width:220px;height:30px;'id='updateNode' lay-verify='required' placeholder='请输入微圈分类名称'>"
                + "</div></form>",
            btn: ['确定', '取消'],
            yes: function () {
                var artcleCategroyName = $("#updateNode").val();
                var jsActicleCategroy = {
                    'acticleCategroyId': acticleCategroyId,
                    'artcleCategroyName': artcleCategroyName,
                    'updateId': createId
                }
                if (artcleCategroyName.length != 0) {
                    $.ajax({
                        url: '/acticleCategroy/updateActicleCategroy',
                        type: 'post',
                        data: jsActicleCategroy,
                        dataType: 'json',
                        success: function (data) {
                            if (data.data) {
                                layer.msg("修改成功");
                                document.location.reload();
                                return true;
                            } else {
                                layer.msg("修改失败");
                                return false;
                            }
                        }
                    });
                } else {
                    layer.msg("不能为空");
                }
            }
        });
    }
    //加载树
    var zTree, rMenu;
    $(document).ready(function () {
        $.ajax({
            url: "/acticleCategroy/getTree",
            type: 'post',
            dataType: 'json',
            success: function (data) {
                zTree = $.fn.zTree.init($("#ztree"), settingss, data.data); //初始化树
                zTree.expandAll(true);   //true 节点全部展开、false节点收缩
            }
        })
        rMenu = $("#rMenu");
    });

    //点击节点，展示对应类别下微圈信息
    function chooseNode(event, treeId, treeNode) {
        var acticleCategroyId = treeNode.acticleCategroyId;
        tableIns.reload({
            where: {
                'acticleCategroyId': acticleCategroyId
            }
        });
    }

    //加载表格
    var tableIns;
    tableIns = table.render({
        elem: '#table',
        id:'idTest',
        url: '/microcircle/getMicrocircleTable',
        title: '微圈列表',
        toolbar: '#toolbar',
        page: {
            limit: 10,
            layout: ['count', 'prev', 'page', 'next', 'skip', 'refresh'],
            first: '首页',
            last: '尾页'
        },
        cols: [
            [
                {type: 'checkbox'},
                {
                    field: '', title: '序号', align: 'center', templet: function (data) {
                        return data.LAY_INDEX;
                    }
                },
                {field: 'nickname', title: '用户名称', align: 'center'},
                {field: 'artcleTitle', title: '文章标题', align: 'center'},
                {field: 'createDate', title: '创建时间', align: 'center'},
                {field: 'account', title: '用户账号', align: 'center'},
                {field: 'acticleLike', title: '点赞数量', align: 'center'},
                {field: 'colCount', title: '收藏数量', align: 'center'},
                {field: 'acticleReviews', title: '评论数量', align: 'center'},
                {field: 'acticleShare', title: '分享数量', align: 'center'},
                {
                    field: '', title: '操作', align: 'center', templet: function (data) {
                        return "<div><a style='color: #2F4056' href='javascript:getinformation(" + data.microcircleId + ")'>查看</a><a href='javascript:deleteMicrocircle(\"" + data.microcircleId + "\",\"" + data.artcleTitle + "\")' style='color: #2F4056;margin-left: 10px'>删除</a></div>"
                    }
                }
            ]
        ],
    });
    //查看微圈
    getinformation = function getinformation(id) {
        localStorage.setItem('microcircleId', id);
        $.ajax({
            url: '/microcircle/getMicrocircleById',
            type: 'post',
            dataType: 'json',
            data: {'microcircleId': id, 'userId': createId},
            success: function (data) {
                viewDetails(data.data);
            }
        });
    }

    function viewDetails(data) {
        layer.open({
            type: 2,
            title: '查看微圈信息',
            shade: 0,
            area: ['1000px', '500px'],
            offset: 't',
            maxmin: true,
            btn: ['关闭'],
            content: '/microcircle/microcircle-see.html',
            success: function (layero, index) {
                var obj = layero.find('iframe').contents();
                var artcleUrl = "http://"+data.artcleUrl;
                obj.find('#artcleUrl').attr('src', artcleUrl);
                obj.find('#name').text(data.nickname);
                obj.find('#createName').text(data.nickname);
                obj.find('.artcleTitle').text(data.artcleTitle);
                obj.find('#artcleCategroyName').text(data.artcleCategroyName);
                obj.find('#createDate').text(data.createDate);
                obj.find('#createAccount').text(data.account);
                obj.find('#article').html(data.article);
                obj.find('#acticleHits').text(data.acticleHits);
                obj.find('#acticleLike').text(data.acticleLike);
                obj.find('#acticleShare').text(data.acticleShare);
                obj.find('#colCount').text(data.colCount);
                var trueName = localStorage.getItem("trueName");
                obj.find('input[name=trueName]').val(trueName);
                var account = localStorage.getItem("account");
                obj.find('input[name=account]').val(account);
                obj.find('#microcircleId').val(data.microcircleId);
            }
        });
    }

    //删除微圈
    deleteMicrocircle = function deleteMicrocircle(id, artcleTitle) {
        layer.confirm('是否删除' + artcleTitle + '微圈', {
            icon: 3, title: '提示'
        }, function (index) {
            $.ajax({
                url: '/microcircle/deleteMicrocircle',
                type: 'post',
                dataType: 'json',
                data: {'microcircleId': id, 'userId': createId},
                success: function (data) {
                    if (data.data) {
                        $.ajax({
                            url: '/record/deleteRecord',
                            type: 'post',
                            dataType: 'json',
                            data: {'courseId': id, 'type': 4},
                            success: function (data) {
                                if (data.data) {
                                    layer.msg("删除成功");
                                    getTable();
                                } else {
                                    layer.msg("删除失败")
                                }
                            }
                        });
                    } else {
                        layer.msg("删除失败")
                    }
                }
            });
        })
    }
    //搜索
    form.on('submit(search)', function (data) {
        tableIns.reload({
            where: {
                'artcleTitle': data.field.artcleTitle,
                'nickname': data.field.nickname,
                'account': data.field.account
            }
        });
    })
    //重置
    $('#reset').click(function () {
        $('input[name=artcleTitle]').val('');
        $('input[name=nickname]').val('');
        $('input[name=account]').val('');
        tableIns.reload({
            where: {
                'artcleTitle': '',
                'nickname': '',
                'account': ''
            }
        });
    });
    //返回
    goBack = function goBack() {
        //跳转课程列表
        parent.$('#Jump').val('首页');
        parent.getQuick();
        return;
    }
})
